﻿/*******************************************************
 * 
 * 作者：胡庆访
 * 创建时间：20130326 16:08
 * 说明：此文件只包含一个类，具体内容见类型注释。
 * 运行环境：.NET 4.0
 * 版本号：1.0.0
 * 
 * 历史记录：
 * 创建文件 胡庆访 20130326 16:08
 * 
*******************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace MSDNConverter
{
    public class CacheReader : MSDNReader
    {
        private string Directory
        {
            get { return RootId + "_Cache\\"; }
        }

        private string XmlFileName
        {
            get { return Path.Combine(Directory, "articles.xml"); }
        }

        private string FileName(RawArticle article)
        {
            return Path.Combine(Directory, article.Id + ".html");
        }

        protected override RawArticle ReadArticleSchema()
        {
            System.IO.Directory.CreateDirectory(this.Directory);

            if (File.Exists(XmlFileName))
            {
                var xml = File.ReadAllText(XmlFileName);
                var root = RawArticle.FromXml(xml);
                return root;
            }
            else
            {
                var root = base.ReadArticleSchema();
                var xml = root.ToXml();
                File.WriteAllText(XmlFileName, xml);
                return root;
            }
        }

        protected override void ReadContentSingle(RawArticle item)
        {
            var fileName = FileName(item);
            if (File.Exists(fileName))
            {
                item.RawHtml = File.ReadAllText(fileName);
            }
            else
            {
                base.ReadContentSingle(item);
                File.WriteAllText(fileName, item.RawHtml);
            }
        }

        /// <summary>
        /// 返回图片的全路径
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        internal string GetImageFile(string url)
        {
            var fileName = url.Replace(":", "_").Replace("/", "_");
            var file = Path.Combine(Directory, fileName);

            file = Path.Combine(AppDomain.CurrentDomain.SetupInformation.ApplicationBase, file);

            if (!File.Exists(file))
            {
                Console.WriteLine("downloading image: " + url);
                this.Client.DownloadFile(url, file);
            }

            return file;
        }
    }
}
